package com.ingdan.contactdemo;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ingdan.contactdemo.view.EditTextWithDel;
import com.ingdan.contactdemo.view.PinyinComparator;
import com.ingdan.contactdemo.view.PinyinUtils;
import com.ingdan.contactdemo.view.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements View.OnClickListener {

    Button mButton2,mButton;
 
    LinearLayout mLinearLayout;
    private SideBar sideBar;
    private EditTextWithDel mEtSearchName;
    ListView mRv;
    private TextView dialog;
    private ContactAdapter mContactAdapter;
List<Person>     list = new ArrayList<Person>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         mButton =(Button) findViewById(R.id.button);
         mButton2 =(Button) findViewById(R.id.button2);
         mLinearLayout =(LinearLayout) findViewById(R.id.linearLayout);
         mEtSearchName = (EditTextWithDel) findViewById(R.id.et_search);
         sideBar = (SideBar) findViewById(R.id.sidrbar);
         dialog = (TextView) findViewById(R.id.dialog);
         mRv =(ListView) findViewById(R.id.lv);
        queryContactsShowData();

        initDatas();
        initEvents();
        setAdapter();
    }
    private void initDatas() {
        sideBar.setTextView(dialog);
    }

   
    private void initEvents() {
    	  mButton.setOnClickListener(this);
          mButton2.setOnClickListener(this);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mContactAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                	mRv.setSelection(position + 1);
                }
            }
        });
    
  
 

        //根据输入框输入值的改变来过滤搜索
        mEtSearchName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    	mRv.setOnItemLongClickListener( new OnItemLongClickListener() {

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
		 DialogUtils.showDialog(MainActivity.this, "提示", "是要删除此联系人", "取消", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {

             }
         }, "确定", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {
                 deleteContact(list.get(position).getName(), position);

             }
         });
		return false;
	}
});
    
        mRv.setOnItemClickListener( new OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		  Log.d("MainActivity", "mContactList.get(position):" + list.get(position));
          Intent intent = new Intent(MainActivity.this,AddActivity.class);
          intent.putExtra(AddActivity.TYPETAG, 1);
          intent.putExtra(AddActivity.LINKNAME,list.get(position).getName());
          intent.putExtra(AddActivity.LINKPHONE,list.get(position).getPhone());
          intent.putExtra(AddActivity.NO,String.valueOf(list.get(position).getContact_id()));

          startActivity(intent);
		
	}
});
    }
    private void setAdapter() {
        list= filledData(list);
        Collections.sort(list, new PinyinComparator());
        mContactAdapter = new ContactAdapter(MainActivity.this, list);
        mRv.setAdapter(mContactAdapter);

    }


    /**
     * 查询手机联系人并显示
     */
    private void queryContactsShowData() {
        list.clear();
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor == null) {
            return;
        }
        while (cursor.moveToNext()) {
            Person p = new Person();


            p.setName( cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            p.setPhone(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            p.setContact_id(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID))));
        list.add(p);
        }
        cursor.close();
      

    }


    /**
     * 删除联系人
     */
    private void deleteContact(String name, int position) {


        //根据姓名求id
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data._ID}, "display_name=?", new String[]{name}, null);
        if (cursor == null) {
            return;
        }

        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            //根据id删除data中的相应数据
            resolver.delete(uri, "display_name=?", new String[]{name});
            uri = Uri.parse("content://com.android.contacts/data");
            resolver.delete(uri, "raw_contact_id=?", new String[]{id + ""});
            Toast.makeText(this, "删除号码成功", Toast.LENGTH_SHORT).show();
            list.remove(position);
            mContactAdapter.updateListView(list);
            mContactAdapter.notifyDataSetChanged();

        } else {
            Toast.makeText(this, "没有找到号码", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            //查询所有数据
            case R.id.button:

                break;
            //写入
            case R.id.button2:
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                intent.putExtra(AddActivity.TYPETAG, 0);
                startActivity(intent);
                break;

            default:
                break;
        }
    }


    private  void query(){
        list.clear();
        queryContactsShowData();
        list= filledData(list);
        Collections.sort(list, new PinyinComparator());
        mContactAdapter.notifyDataSetChanged();
        mContactAdapter.updateListView(list);

    }
    
    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<Person> mSortList = new ArrayList<Person>();
        if (TextUtils.isEmpty(filterStr)) {
            mSortList = list;
        } else {
            mSortList.clear();
            for (Person sortModel : list) {
                String name = sortModel.getName();
                if (name.toUpperCase().contains(filterStr.toUpperCase()) || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
                    mSortList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinComparator());
        mContactAdapter.updateListView(mSortList);
    }

    private List<Person> filledData(List<Person> date) {
        List<Person> mSortList = new ArrayList<Person>();
        ArrayList<String> indexString = new ArrayList<String>();

        for (int i = 0; i < date.size(); i++) {
        	Person sortModel = new Person();
            sortModel.setName(date.get(i).getName());
            sortModel.setContact_id(date.get(i).getContact_id());
            sortModel.setPhone(date.get(i).getPhone());
            String pinyin = PinyinUtils.getPingYin(list.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }
            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        query();
    }
}
